<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="15">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['group:actRecord:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['group:actRecord:update']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['group:actRecord:deletes']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['group:actRecord:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            :disabled="single"
            v-if="permitUpdate()>0"
            type="warning"
            plain
            @click="computeCost"
            v-hasPermi="['group:actRecord:findDetail']"
        >球费计算
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange"
              :scrollbar-always-on="true">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="录入时间" align="center" prop="createTime" width="120px">
        <template #default="scope">
          {{ format(scope.row.createTime, 'yyyy-MM-dd') }}
        </template>
      </el-table-column>
      <el-table-column v-if="!queryParams.groupId" label="群名称" align="center" prop="groupName"/>
      <el-table-column label="活动内容" align="center" prop="txtContent" :show-overflow-tooltip="true"/>
      <el-table-column label="有效活动" align="center">
        <template #default="scope">
          <dict-tag :options="group_login_default" :value="scope.row.validStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="人数" align="center" prop="joinNum">
        <template #default="scope">
          <el-button link type="primary" icon="Link" v-hasPermi="['group:participator:listPage']"
                     @click="skipPage(scope.row,'/group/participator')">
            {{ scope.row.joinNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="男生费用" align="center" prop="fullMaleCost"/>
      <el-table-column label="女生费用" align="center" prop="fullFemaleCost"/>
      <el-table-column label="场地总价" align="center" prop="siteTotalCost"/>
      <el-table-column label="球总花费" align="center" prop="ballTotalCost"/>
      <el-table-column label="总花费 " align="center" prop="totalCost"/>
      <el-table-column label="男生人数" align="center" prop="fullMaleNum"/>
      <el-table-column label="女生人数" align="center" prop="fullFemaleNum"/>
      <el-table-column label="女生优惠" align="center" prop="femaleDiscountPrice"/>
      <el-table-column label="场地数" align="center" prop="siteNum"/>
      <el-table-column label="场地单价" align="center" prop="sitePerPrice"/>
      <el-table-column label="时长" align="center" prop="timeLength"/>
      <!--      <el-table-column label="额外每人" align="center" prop="extraPerCost"/>-->
      <!--      <el-table-column label="额外固定" align="center" prop="extraFixedCost"/>-->
      <el-table-column label="使用球数" align="center" prop="costBallNum"/>
      <el-table-column label="每桶球数" align="center" prop="bucketBallNum"/>
      <el-table-column label="每桶球价" align="center" prop="bucketPerPrice"/>
      <el-table-column label="球费计算 " align="center">
        <template #default="scope">
          <dict-tag :options="group_login_default" :value="scope.row.settlementFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="收费方式" align="center" prop="collectType">
        <template #default="scope">
          <dict-tag :options="group_collect_type" :value="scope.row.collectType"/>
        </template>
      </el-table-column>
      <el-table-column label="免费人数" align="center" prop="feeNum"/>
      <el-table-column label="半男人数" align="center" prop="halfMaleNum"/>
      <el-table-column label="半女人数" align="center" prop="halfFemaleNum"/>
      <el-table-column label="飞机人数" align="center" prop="fullAbsentNum"/>
      <el-table-column label="半飞人数" align="center" prop="halfAbsentNum"/>

      <!--      <el-table-column label="租户编号" align="center" prop="tenantId"/>-->
      <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-if="permitUpdate(scope.row.groupId)>0  && scope.row.validStatus===0"
                     v-hasPermi="['group:actRecord:update']">修改
          </el-button>
          <el-button link type="primary" icon="Eye" @click="detailF=true;handleUpdate(scope.row)"
                     v-if="permitUpdate(scope.row.groupId)>0  && scope.row.validStatus===1"
                     v-hasPermi="['group:actRecord:findDetail']">详情
          </el-button>
          <el-button link type="primary" icon="Edit" @click="skipPage(scope.row,'/group/calculate')"
                     v-if="permitUpdate(scope.row.groupId)>0  && scope.row.validStatus===1"
                     v-hasPermi="['group:actRecord:findDetail']">球费计算
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-if="permitUpdate(scope.row.groupId)>0"
                     v-hasPermi="['group:actRecord:delete']">删除
          </el-button>
          <!--          <el-button type="primary" @click="computeCost">球费计算</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改群发布活动记录对话框 -->
    <el-dialog :title="title" v-model="open" width="580px" append-to-body :show-close="detailF"
               @closed="detailF=false;parseRes=[];showParse=false">
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="选择群" prop="groupId" v-if="!queryParams.groupId>0">
          <el-col :span="12">
            <el-form-item prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择" :disabled="form.id>0 || queryParams.groupId>0">
                <el-option
                    v-for="dict in userGroups"
                    :key="dict.id"
                    :label="dict.groupName"
                    :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="活动文本内容">
          <el-button v-if="form.id" class="mgr-8" size="small" type="primary" @click="copy(form.txtContent)">复制
          </el-button>
          <el-input v-model="form.txtContent" style="width: 240px"
                    type="textarea"
                    :autosize="true"
                    placeholder="Please input"/>
        </el-form-item>
        <el-form-item label="有效状态" v-if="form.validStatus!=3">
          <el-radio-group v-model="form.validStatus">
            <el-radio
                v-for="dict in group_login_default"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="!detailF">
          <el-button type="primary" @click="parseForm">解 析</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <el-table v-if="showParse" :data="parseRes">
        <el-table-column label="排序" align="center" prop="sortNum"/>
        <el-table-column label="名称" align="center" prop="userName"/>
        <el-table-column label="性别" align="center">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import * as actRecordServer from "@/api/group/actRecord.js";
import * as groupServer from "@/api/group/group.js";
import {AES_Decrypt, AES_Encrypt} from "@/utils/jsencrypt.js";
import useClipboard from "vue-clipboard3";
import {format} from 'date-fns';
import Link from "@/layout/components/Sidebar/Link.vue";

const {toClipboard} = useClipboard()
const detailF = ref(false);
const {proxy} = getCurrentInstance();
const {group_collect_type, group_login_default, sys_user_sex, group_find_order}
    = proxy.useDict("group_collect_type", "group_login_default", "sys_user_sex", "group_find_order");
const parseRes = ref([]);
const showParse = ref(false);
const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const selectValue = ref({});
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const router = useRouter();
const route = useRoute();
const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const resetFlag = ref(false);
const userGroups = ref([])
const groupPermitMap = reactive(new Map())
const data = reactive({
  form: {},
  queryParams: {
    orderByColumn: 'id',
    isAsc: 'desc',
    pageNum: 1,
    pageSize: 10,
    groupId: groupId.value,
    txtContent: null,
    joinNum: null,
    feeNum: null,
    fullMaleNum: null,
    fullFemaleNum: null,
    fullMaleCost: null,
    fullFemaleCost: null,
    halfMaleNum: null,
    halfFemaleNum: null,
    fullAbsentNum: null,
    halfAbsentNum: null,
    settlementFlag: null,
    totalCost: null,
    collectType: null,
    fixedMale: null,
    fixedFemale: null,
    femaleDiscountPrice: null,
    siteNum: null,
    sitePerPrice: null,
    siteTotalCost: null,
    ballTotalCost: null,
    timeLength: null,
    extraPerCost: null,
    extraFixedCost: null,
    costBallNum: null,
    bucketBallNum: null,
    bucketPerPrice: null,
    validStatus: null,
    tenantId: null,
    startTime: null,
    findTime: null,
    endTime: null,
  },
  rules: {
    groupId: [
      {required: true, message: "群id不能为空", trigger: "blur"}
    ],
    txtContent: [
      {required: true, message: "活动文本内容不能为空", trigger: "blur"}
    ],
  }
});

function skipPage(row, path) {
  // //console.log(row,"row");
  router.push({path: path, query: {activityId: AES_Encrypt(row.id), groupId: AES_Encrypt(row.groupId)}});
}

const {queryParams, form, rules} = toRefs(data);
const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
      userGroups.value = res.data
      userGroups.value.forEach(item => {
        groupPermitMap.set(item.id, item.adminType)
      })
      if (!groupId.value && !resetFlag.value) {
        userGroups.value.forEach(item => {
          if (item.loginDefault === 1) {
            groupId.value = item.id
            queryParams.value.groupId = item.id
          }
        })
      }
      if (!groupId.value && !resetFlag.value) {
        groupId.value = userGroups.value[0].id
        queryParams.value.groupId = userGroups.value[0].id
      }
    }).then(() => {
      // //console.log("start",currentAdmin.value)
      resolve()
    })
  })
})

function permitUpdate(groupId) {
  if (!groupId) {
    groupId = queryParams.value.groupId
  }
  return groupPermitMap.get(groupId)
}

/** 查询群发布活动记录列表 */
function getList() {
  loading.value = true;
  start().then(() => {
    if (queryParams.value.findTime) {
      queryParams.value.endTime = queryParams.value.findTime[1]
      queryParams.value.startTime = queryParams.value.findTime[0]
    }
    actRecordServer.listRecord(queryParams.value).then(response => {
      recordList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

const copy = (text) => {
  toClipboard(text).then(() => {
    proxy.$modal.msgSuccess('复制成功');
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  showParse.value = false;
  parseRes.value = [];
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    groupId: groupId.value ? groupId.value : null,
    txtContent: null,
    joinNum: 0,
    feeNum: null,
    fullMaleNum: null,
    fullFemaleNum: null,
    fullMaleCost: null,
    fullFemaleCost: null,
    halfMaleNum: null,
    halfFemaleNum: null,
    fullAbsentNum: null,
    halfAbsentNum: null,
    settlementFlag: null,
    totalCost: null,
    collectType: 0,
    fixedMale: null,
    fixedFemale: null,
    femaleDiscountPrice: null,
    siteNum: null,
    sitePerPrice: null,
    siteTotalCost: null,
    ballTotalCost: null,
    timeLength: null,
    extraPerCost: null,
    extraFixedCost: null,
    costBallNum: null,
    bucketBallNum: null,
    bucketPerPrice: null,
    validStatus: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null,
  };
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.groupId = undefined;
  form.value.groupId = undefined;
  groupId.value = null
  resetFlag.value = true;
  queryParams.value.startTime = null;
  queryParams.value.findTime = null;
  queryParams.value.endTime = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  if (!single.value) {
    console.log(selection[0]);
    selectValue.value = selection[0];
  }
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.groupId = queryParams.value.groupId
  open.value = true;
  title.value = "添加群发布活动记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]
  actRecordServer.getRecord({id: _id}).then(response => {
    form.value = response.data;
    form.value.validStatus = response.data.validStatus === 1 ? 3 : 0;
    open.value = true;
    if(form.value.validStatus===0){
      title.value = "修改群发布活动记录";
    }else{
      detailF.value = true;
      title.value = "活动记录详情";
    }


  });
}

/** 解析按钮 */
function parseForm() {
  actRecordServer.parseTxt({txtContent: form.value.txtContent, groupId: form.value.groupId}).then(response => {
    proxy.$modal.msgSuccess("解析成功");
    parseRes.value = response.data;
    showParse.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        actRecordServer.updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          showParse.value = false;
          parseRes.value = [];
          recordList.value = [];
          getList();
        });
      } else {
        actRecordServer.addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          showParse.value = false;
          parseRes.value = [];
          getList();
        });
      }
    }
  });
}

function computeCost() {
  if (selectValue.value.validStatus !== 1) {
    proxy.$modal.msgSuccess("不是有效活动不能计算费用！");
    return
  }
  skipPage(selectValue.value, '/group/calculate')
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除群发布活动记录编号为"' + _ids + '"的数据项？').then(function () {
    return actRecordServer.delRecord({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

getList();
</script>
